package gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class UrlTransformLogFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 记录原始请求信息
        String originalPath = exchange.getRequest().getURI().getPath();
        String originalQuery = exchange.getRequest().getURI().getQuery();
        String method = exchange.getRequest().getMethod().name();

        log.info("=== Gateway URL转换日志 ===");
        log.info("原始请求 - 方法: {}, 路径: {}, 参数: {}",
                method, originalPath, originalQuery);
        log.info("请求头: {}", exchange.getRequest().getHeaders());

        // 继续处理
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            // 记录转换后的信息（如果有重写）
            log.info("响应状态: {}", exchange.getResponse().getStatusCode());
            log.info("=== 结束 ===");
        }));
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}